<?php

namespace app\api\controller;

use app\BaseController;
use app\common\traits\JumpTrait;
use EasyWeChat\Factory;
use think\facade\Log;
use think\facade\Session;

//class Login extends Api
class Login extends BaseController
{
    use JumpTrait;
    /**
     * @title 微信授权回调
     * @author FashionJune
     */
    public function oauthCallback()
    {
        $wechat = Factory::officialAccount([
            'app_id' => env('WECHAT.APP_ID'),
            'secret' => env('WECHAT.SECRET'),
        ]);
        try {
            $user = $wechat->oauth->userFromCode(input('code'))->toArray();
        } catch (\Exception $e) {
            Log::write('oathCallback_failed:' . $e->getMessage(), 'api-login-error');
            die('获取用户信息失败');
        }
//        try {
//            $user = $this->wechat->oauth->userFromCode(input('code'))->toArray();
//        } catch (\Exception $e) {
//            Log::write('oathCallback_failed:' . $e->getMessage(), 'api-login-error');
//            die('获取用户信息失败');
//        }
        session('wechat_user', $user);
        $targetUrl = session('target_url') ?? 'index';
        Session::save();
        $this->redirect($targetUrl);
//        $user = [
//            "id" => "o2WJR6laUql__8AVyOGlMd4UYjCw",
//            "name" => "煤球的御用营养师",
//            "nickname" => "煤球的御用营养师",
//            "avatar" => "https://thirdwx.qlogo.cn/mmopen/vi_32/ajNVdqHZLLABdQ0q7Jue3oNgknh4YeHwLxOqz6hQ1krcsG0CBp6OICDLy4KiaaILgics32xEAFa8YkzFaiavxPDKA/132",
//            "email" => null,
//            "raw" => [
//                "openid" => "o2WJR6laUql__8AVyOGlMd4UYjCw",
//                "nickname" => "煤球的御用营养师",
//                "sex" => 1,
//                "language" => "zh_CN",
//                "city" => "郑州",
//                "province" => "河南",
//                "country" => "中国",
//                "headimgurl" => "https://thirdwx.qlogo.cn/mmopen/vi_32/ajNVdqHZLLABdQ0q7Jue3oNgknh4YeHwLxOqz6hQ1krcsG0CBp6OICDLy4KiaaILgics32xEAFa8YkzFaiavxPDKA/132",
//                "privilege" => [],
//            ],
//            "access_token" => "41_xCIHzHmikPkR1-mDsZ99mZ1mnrn7DIvAUZygxZ-M1RzGw-1IT6ZSxNJ7IQT79AC7RxWnbXWfYTo49992Wa7tuA",
//            "refresh_token" => "41_NrgcOKVj9QiNwI1z2LNX7oPnbWuztiYaMY309YRIYAMO0ztjFrRtsvDoqcOJSZXNNxBFYyQwpDWjjEhrjpCHxw",
//            "expires_in" => 7200,
//        ];
    }
}
